package cn.com.goldhs.architecture.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;

import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.widgets.TreeItem;

public class TreeItemTransfer extends ByteArrayTransfer {

	private static final String TypeTreeItem = "TypeTreeItem" + Calendar.getInstance().getTimeInMillis();
	private static final int TypeIdTreeItem = registerType(TypeTreeItem);

	private static TreeItemTransfer mInstance = new TreeItemTransfer();

	
	public static TreeItemTransfer getInstance() {
		return mInstance;
	}
	
	@Override
	public void javaToNative(Object object, TransferData transferData) {
		
		if (object == null || !(object instanceof TreeItem[]))
			return;

		if (isSupportedType(transferData)) {
			TreeItem[] items = (TreeItem[]) object;
			try {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				ObjectOutputStream writeOut = new ObjectOutputStream(out);
				writeOut.writeObject(items);
				byte[] buffer = out.toByteArray();
				writeOut.close();

				super.javaToNative(buffer, transferData);

			} catch (IOException e) {
			}
		}
	}

	@Override
	public Object nativeToJava(TransferData transferData) {

		if (isSupportedType(transferData)) {

			byte[] buffer = (byte[]) super.nativeToJava(transferData);
			if (buffer == null)
				return null;

			TreeItem[] items = null;
			try {
				ByteArrayInputStream in = new ByteArrayInputStream(buffer);
				ObjectInputStream readIn = new ObjectInputStream(in);
				items = (TreeItem[]) readIn.readObject();
			} catch (Exception ex) {
				return null;

			}
			return items;
		}
		
		return null;
	}

	protected String[] getTypeNames() {
		return new String[] { TypeTreeItem };
	}

	protected int[] getTypeIds() {
		return new int[] { TypeIdTreeItem };
	}
}
